﻿using FourSquare.SharpSquare.Entities;
using FoursquareTask.Exceptions;
using FoursquareTask.TOs;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace FoursquareTask.Helpers
{
    public class RequestHelper
    {
        private const string CLIENT_ID = "U0HDWP5UTXXTGNIJ5MGNHDZNTG4BIUQ3HNFTSU3GIVPTCP2R";
        private const string CLIENT_SECRET = "UPWAY1U1VK4K4F4R0G1M2ZAVTASOJGBUP5WI423XZEZS12PX";

        public List<Venue> FindVenues(string text)
        {
            List<Venue> found = new List<Venue>();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(SearchQueryBuilder(text));
            request.Accept = "application/json";

            try
            {
                using (WebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                    {
                        string responseText = sr.ReadToEnd();
                        JObject json = JObject.Parse(responseText);
                        IList<JToken> tokens = json["response"]["venues"].Children().ToList();
                        foreach (JToken token in tokens)
                        {
                            Venue venn = JsonConvert.DeserializeObject<Venue>(token.ToString());
                            found.Add(venn);
                            
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                throw new FoursquareException("Error contacting Foursquare API", ex);
            }
            return found;
        }

        public List<VenueTO> GetVenuesDetails(IEnumerable<Venue> venues)
        {
            List<VenueTO> tos = new List<VenueTO>();
            foreach (Venue ven in venues)
            {
                HttpWebRequest detailsRequest = (HttpWebRequest)WebRequest.Create(DetailsQueryBuilder(ven.id));
                detailsRequest.Accept = "application/json";

                try
                {
                    using (WebResponse response = (HttpWebResponse)detailsRequest.GetResponse())
                    {
                        using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                        {
                            string text = sr.ReadToEnd();
                            JObject json = JObject.Parse(text);

                            string url = json["response"]["venue"]["canonicalUrl"].ToString();
                            string hereNow = json["response"]["venue"]["hereNow"]["count"].ToString();
                            string checkins = json["response"]["venue"]["stats"]["checkinsCount"].ToString();
                            VenueTO myTo = (new VenueConverter()).Venue2TO(ven);
                            myTo.CanonicalUrl = url;
                            myTo.HereNow = hereNow;
                            myTo.Checkins = checkins;
                            tos.Add(myTo);
                        }
                    }
                }
                catch (WebException ex)
                {
                    throw new FoursquareException("Error contacting Foursquare API", ex);
                }                
            }
            return tos;
        }



        private string SearchQueryBuilder(string text)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("https://api.foursquare.com/v2/venues/search?near=Brno&query=");
            sb.Append(text);
            sb.Append("&client_id=");
            sb.Append(CLIENT_ID);
            sb.Append("&client_secret=");
            sb.Append(CLIENT_SECRET);
            sb.Append("&v=20130815");            
            return sb.ToString();
        }

        private string DetailsQueryBuilder(string venueId)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("https://api.foursquare.com/v2/venues/");
            sb.Append(venueId);
            sb.Append("?client_id=");
            sb.Append(CLIENT_ID);
            sb.Append("&client_secret=");
            sb.Append(CLIENT_SECRET);
            sb.Append("&v=20130815");            
            return sb.ToString();
        }
    }
}